package login;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author barre
 */
 class Usuarios {
    Map<String, String> DB = new HashMap<String, String>();
    private final String SALT = "my-salt-text";
    
    //OJO: Ruta a cambiar dependiendo si estas en Linux o Windows.
    //Opcional poner funcion que devuelva el path.
    
    private String path = loadPath();

    //private String path = "C:\\Users\\alumno\\Documents\\NetBeansProjects\\SdCLoginJSP\\src\\java\\files\\usuarios";
    //private String path = "/home/barre/Workspaces/NetBeansProjects/SdCLoginJSP/src/java/files/usuarios";

    File f = new File("usuarios");    
    
    public Usuarios() throws IOException{
        DB = this.readFile(this.path);  
    }

    public Map<String,String> getUsr(String name) {
        return DB;
    }

    public void setUsr(String user, String password) {
        this.register(user, password);
    }
    
    private void register(String username, String password) {
        try {
                FileWriter fw = null;
                String saltedPassword = SALT + password.toLowerCase();
                String hashedPassword = generateHash(saltedPassword);

                File f = new File(path);
                fw = new FileWriter(f,true);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(username.toLowerCase());
                bw.write(" ");
                bw.write(hashedPassword);
                bw.write("\n");
                bw.close();
                fw.close();

                DB.put(username.toLowerCase(), hashedPassword);
        } catch (IOException ex) {
            Logger.getLogger(Usuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }
    
    Boolean login(String username, String password) {
		Boolean isAuthenticated = false;
                
		// remember to use the same SALT value use used while storing password
		// for the first time.
		String saltedPassword = SALT + password;
		String hashedPassword = generateHash(saltedPassword);
                //String hashedPassword = password;
                
		String storedPasswordHash = DB.get(username.toLowerCase());
		if(hashedPassword.equals(storedPasswordHash)){
			isAuthenticated = true;
		}else{
			isAuthenticated = false;
		}
		return isAuthenticated;
    }

    private static String generateHash(String input) {
                StringBuilder hash = new StringBuilder();

		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = sha.digest(input.getBytes());
			char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'a', 'b', 'c', 'd', 'e', 'f' };
			for (int idx = 0; idx < hashedBytes.length; ++idx) {
				byte b = hashedBytes[idx];
				hash.append(digits[(b & 0xf0) >> 4]);
				hash.append(digits[b & 0x0f]);
			}
		} catch (NoSuchAlgorithmException e) {
			// handle error here.
		}

		return hash.toString();
    }

    private Map<String, String> readFile(String path) {
        FileReader fr = null;
        TreeMap<String,String> usr = new TreeMap<String, String>();
        try {
            fr = new FileReader(path);
            BufferedReader bfr = new BufferedReader(fr);
            String line = bfr.readLine();
            int j = 0;
            String user = null,pass = null;
            StringTokenizer st;
            while(line!=null){
                st = new StringTokenizer(line, " ");
                while(st.hasMoreTokens()){
                    user = st.nextToken().toLowerCase();
                    pass = st.nextToken().toLowerCase();
                }
                usr.put(user, pass);
                line = bfr.readLine();
            }
            bfr.close();
            fr.close();
            /*System.out.println("Map Values Before: ");
            Set keys = usr.keySet();
            for (Iterator i = keys.iterator(); i.hasNext();) {
                String key = (String) i.next();
                String value = (String) usr.get(key);
                System.out.println(key + " = " + value);
            }*/
        }
        catch (IOException ex) {
            Logger.getLogger(Usuarios.class.getName()).log(Level.SEVERE, null, ex);
        }        
        return usr;
    }    
    
    boolean registered(String user) {
        return DB.containsKey(user.toLowerCase());
    }

    private String loadPath() {
         String fileSep = "/"; //System.getProperty("file.separator"); 
        String p;
        URL res = getClass().getClassLoader().getResource("files/usuarios");
        p = res.toString();
        p = p.substring(0, p.lastIndexOf(fileSep));
        p = p.substring(0, p.lastIndexOf(fileSep));
        p = p.substring(0, p.lastIndexOf(fileSep));
        p = p.substring(0, p.lastIndexOf(fileSep));
        p = p.substring(0, p.lastIndexOf(fileSep));
        p = p.substring(0, p.lastIndexOf(fileSep));
        if(p.startsWith("/")){
            p = p.substring(p.indexOf(fileSep)+1, p.length());
        }else{
            p = p.substring(p.indexOf(fileSep), p.length());
        }
        p = p.replaceAll("%20"," ");
        return p+fileSep+"src"+fileSep+"java"+fileSep+"files"+fileSep+"usuarios";
    }
 }